<?php

class _register
{
	public function initc(){}

	public function index()
	{
        $from = Request::Get('from');
        if (!empty($from)) {
            $from = ltrim(urldecode($from));
        } else {
            $from = '';
        }
        
		if (IS_POST) {

            $username         = Request::Post('username', '');
            $mobile           = Request::post('mobile', '');
            $password         = Request::Post('password');
            $password_confirm = Request::Post('password_confirm');
            $vcode            = Request::Post('vcode');
            $remember_me      = Request::post('remember_me');
            $from             = Request::post('from');
            $invcode          = Request::post('invcode');
            $is_admin         = Request::post('is_admin', 0);

			if ( strcmp($password, $password_confirm) != 0) {
                Response::error('您输入的两个密码不一样, 请重新输入');
			} else if (REQUEST_TIME - $_SESSION['reg_vcode_lasttime'] < 3) {
                $_SESSION['reg_vcode_lasttime'] = REQUEST_TIME;
                Response::error('操作太频繁, 请稍后操作');
            } else if (strtolower($vcode) != strtolower($_SESSION['reg_vcode'])) {
                Response::error('验证码不正确, 请重新输入');
			} else {
                $_SESSION['reg_vcode'] = Fun::randCode();//用完后更换一个随机码
				//$password = password_hash($password, PASSWORD_BCRYPT);
                $password = User::makePassword($password);
			}

			if ($mobile) {
				$mobile = password_hash($mobile, PASSWORD_BCRYPT);
			}

			$expire = $remember_me ? 86400*7 : 86400;
            $unid = UniqueCode::getUserCode();
            
			$user = array(
				'unid' => $unid,
				'username' => $username,
				'password' => $password,
				'mobile' => $mobile,
				'reg_from' => PROJECT_NAME,
			);

			//入库
			$uid = User::link('user')->insert($user)->insertId;
			$user = ['username' => $username, 'uid' => $uid, 'unid'=>$unid, 'from' => $from];
			User::setUserCookie($user, $expire);

			User::afterRegister($unid);

            Response::success($user, '注册成功');
		} else {
		    View::$arrTplVar['from'] = $from;
			View::display('reg');
		}
	}
    
    /**
     * 检查用户名是否重复
     * @throws Exception
     */
	public function isUsernameRepeat()
    {
        if (IS_POST) {
            $username = Request::post('username');
    
            //检测username是否重复
            $already_used = User::link('user')
                ->where(['username' => $username])
                ->count();

            //FileLog::ini('error')->info('检查用户名'. User::$currentSql);
            if ($already_used > 0) {
                Response::error('抱歉~ 您输入的姓名已经被占用, 请重新选择');
            } else {
                Response::success();
            }
        } else {
            Response::error('非法请求');
        }
    }
}